#!/usr/bin/env python
# -*-coding:utf-8-*-
# __author__="life"

import socket,select
import os
import threading
import time
import json
from users import PersonInfo

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# print(BASE_DIR)
HOME_DIR = os.path.join(BASE_DIR,'home')
# TAG = True

inputs = []
outputs = []
messages = {}

def tcplink(conn, addr):
    """
    tcp请求分析函数
    :param conn: tcp连接对象
    :param addr: 连接地址
    :return:
    """
    print('收到来自{0}的连接请求'.format(addr))
    conn.send('与主机通信中...'.encode())
    while True:
        try:
            data = conn.recv(4096).decode()
            # print(data)
            time.sleep(1)
            if not data:            # 数据为空
                break
            else:
                print(data)
                if data == 'ls':    # 接收ls命令
                    P.view_file(conn)
                    continue
                action,filename = data.strip().split()
                # action = action.lower()
                if action == 'put':
                    re = P.Recvfile(conn, filename)
                    if re == True:
                        print('文件接收成功！')
                    else:
                        print('文件接收失败！')
                elif action == 'get':
                    P.Sendfile(conn,filename)
                elif action == 'login':
                    name,password = filename.split(',')
                    P = PersonInfo(name,password)   # 生成用户实例
                    re = P.login()
                    if re == True:
                        conn.send('Ready!'.encode())
                    else:
                        conn.send('False!'.encode())
                elif action == 'register':
                    name,password = filename.split(',')
                    P = PersonInfo(name,password)
                    re = P.register()
                    if re == True:
                        conn.send('Ready!'.encode())
                    else:
                        conn.send('False!'.encode())
                else:
                    print('请求方输入错误!')
                    continue
        except Exception as e:
            print('tcplink处理出现问题',e)
            break
if __name__ == '__main__':
    host = 'localhost'
    port = 8888
    sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sk.bind((host,port))
    sk.listen(5)
    print('服务运行中:正在监听[%s]地址的[%s]端口:'%(host,port))
    inputs = [sk,]

    while True:
        readable_list,writeable_list,error_list = select.select(inputs,outputs,[],1)
        # 接受新连接

        for r in readable_list:
            if r == sk:
                conn, addr = r.accept()
                #创建一个新线程处理tcp连接
                t = threading.Thread(target=tcplink,args=(conn,addr))
                t.start()